

# curl https://gitee.com/lgf1244/scripts/raw/main/shell/system-init.sh | bash
#  (iwr -Uri "https://gitee.com/lgf1244/scripts/raw/main/shell/system-init.ps1").Content | iex
#  (Invoke-WebRequest -Uri "https://gitee.com/lgf1244/scripts/raw/main/shell/system-init.ps1").Content | Invoke-Expression
# iex ((New-Object System.Net.WebClient).DownloadString('https://gitee.com/lgf1244/scripts/raw/main/shell/system-init.ps1'))


# Invoke-WebRequest -Uri "<File URL>" -OutFile "<File Name>"
#吐槽一下这个Uri参数，不应该是Url吗？
#该参数有几个别名，wget、iwr、curl，但在pwsh7.0后wget和curl被取消了，可能开发者也觉得这样凑热度不太好。
# iwr -Uri "<File URL>" -OutFile "<File Name>"

function Test-Command( [string] $CommandName ) {
    (Get-Command $CommandName -ErrorAction SilentlyContinue) -ne $null
}

# if ((Get-Command nu1 -ErrorAction SilentlyContinue) -ne $null) { nu demo.nu }

function demo() {

}

Function _lns ($target, $link) {
  if (Test-Path $link) {
    Remove-Item -Recurse -Force $link
  }

  if (test-path -pathtype container $target) {
    $command = "cmd /c mklink /d " + $link + " " + $target
    # invoke-expression "$command""$link""""$target"""
    invoke-expression "$command"
  }
  elseif (test-path -pathtype Leaf $target) {
    $command = "cmd /c mklink " + $link + " " + $target
    # invoke-expression "$command""$link""""$target"""
    invoke-expression "$command"
  }
  else {
    Write-Output "no such target file or folder"
  }
}

function powershell_setup() {
  # starts with a specific browser
  #Start-Process -FilePath iexplore -ArgumentList www.jb51.net
  # starts with default browser and adds to open browser
  #Start-Process -FilePath www.jb51.net
  #设置
  # powershell对于脚本的执行有着严格的安全限制
  # Get-ExecutionPolicy -List #查看当前的执行策略
  # Set-ExecutionPolicy -Scope CurrentUser RemoteSigned #设置执行策略为要求远程脚本签名，范围为当前用户

  # 策略 Policies：
  # Restricted / AllSigned / RemoteSigned / Unrestricted / Bypass / Undefined

  # 范围 Scopes：
  # Process / CurrentUser / LocalMachine

  # 设置策略#
  # 临时使用，不想修改执行策略为较低的权限，可使用：

  # Set-ExecutionPolicy Bypass -Scope Process -Force; npm-windows-upgrade
  # 开发人员需频繁使用powershell脚本，允许本地脚本运行，可使用：

  Get-ExecutionPolicy -List
  Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
  # Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
  Set-ExecutionPolicy -Scope CurrentUser Bypass
  Set-PSRepository -Name PSGallery -InstallationPolicy Trusted

  #安装必要的模块
  #https://devblogs.microsoft.com/powershell/announcing-psreadline-2-1-with-predictive-intellisense/
  Install-Module PSReadLine -RequiredVersion 2.2.6
  Install-Module ZLocation -Scope CurrentUser
  Install-Module windows-screenfetch
  Install-Module PSColor
  Install-Module DirColors
  Install-Module posh-git
  Install-Module oh-my-posh
  Install-Module npm-completion
  Install-Module Register-Completion
  Import-Module windows-screenfetch
  Import-Module Register-Completion
  Set-PSReadLineOption -PredictionSource History
  # screenfetch  # Get-WmiObject 不能用在 powershell-core中

  # 安装 oh-my-posh : https://ohmyposh.dev/docs/installation/windows
  # winget install JanDeDobbeleer.OhMyPosh -s winget

  # 打开不能使用 chocolatey 安装的软件主页
  # Start-Process -FilePath https://community.chocolatey.org/packages?q=
  # Start-Process -FilePath https://code.visualstudio.com/docs/?dv=win
  # Start-Process -FilePath https://getquicker.net/
  # Start-Process -FilePath https://u.tools/
  # Start-Process -FilePath https://www.wolai.com/lgf136/4fe1sgHUK9MFPZY7TCZrDn
  # Start-Process -FilePath https://www.notion.so/lgf136/Software-bf5441545b80414982fc6d3213ffa566
}

function setup_wsl2() {
  Write-Output "enable wsl2 on windows system now!!!"
  Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
  dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
  dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
  wsl --update
  wsl --set-default-version 2

  # Failed to fetch the list distribution from 'https://raw.githubusercontent.com/microsoft/WSL/master/distributions/DistributionInfo.json'. 无法解析服务器的名称或地址
  # Error code: Wsl/InstallDistro/WININET_E_NAME_NOT_RESOLVED
  # wsl --list --online
  # wsl --install -d Ubuntu
  # wsl --install -d Ubuntu-20.04
  # wsl --install -d Ubuntu-18.04
  # wsl --install -d Ubuntu-16.04
  # wsl --install -d Debian
  # wsl --install -d kali-linux
  # wsl -l -v
  # wsl --shutdown Ubuntu
  # wsl --unregister Ubuntu
  wsl -d Ubuntu -u root eval "Write-Output root:root | chpasswd && sed -i 's@\(archive\|security\).ubuntu.com@mirrors.ustc.edu.cn@g' /etc/apt/sources.list && apt-get update && apt-get upgrade -y && apt-get install -y sudo git openssh-server curl wget aria2 axel bash zsh fish tmux vim neovim nano emacs"
  # wsl -d Alpine -u root eval "Write-Output root:root | chpasswd && sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories && apk add sudo curl wget git bash zsh fish tmux vim neovim nano emacs"
}

function install_chocolatey() {
  # install chocolatey : https://chocolatey.org/install
  ## cmd
  # @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
  ## powershell
  Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
  choco install -y chocolateygui
  # choco install -y --force 7zip
  choco install -y 7zip vim emacs
  choco install -y docker-compose docker-desktop docker-cli docker-machine docker-engine #要先安装 wsl2
  choco install -y multipass virtualbox virtualbox-guest-additions-guest.install vagrant
  # choco install -y git git-lfs git-flow-hooks helix vim neovim emacs emacs-full vcxsrv  vscode sublimetext3 sublimetext4 sublimemerge kate geany
  # choco install -y tencentqq tim wechat wecom listen1.portable netease-cloudmusic obs-studio shotcut fscapture captura ffmpeg gifcam calibre motrix picpick.portable
  # choco install -y weasel 7zip peazip vlc potplayer pandoc rufus autohotkey ditto everything screentog licecap
  # choco install -y steam irfanview mpv shotcut
  # choco install -y nutstore typora  evernote logseq obsidian joplin
  # choco install -y curl wget fd ag fzf bat aria2
  # choco install -y firefox googlechrome vivaldi flashplayerplugin flashplayerppapi
  # choco install -y postman postman-cli anaconda3 nodejs jdk8 python r julia eclipse golang rust rust-analyzer pycharm-community intellijidea-community dbeaver
  # choco install -y sqlite postgresql mysql mysql.workbench mysql-cli sqlitestudio msys2 mongodb.core mongodb-compass mongodb-database-tools mongoclient mongodbfortango
  # choco install -y office-tool powerbi onlyoffice libreoffice-still wps-office-free librecad freecad foxitreader
  # choco install -y mactype qtranslate
  # choco install -y font-awesome-font jetbrainsmononf dejavufonts nerd-fonts-firacode firacode firacodenf nerdfont-hack cascadiacode cascadia-code-nerd-font cascadiafonts cascadiamonopl
  # choco install -y switchhosts wox listary treesizefree ccleaner adwcleaner filezilla filezilla.server
  # choco install -y git msys2 cygwin busybox gow unxutils dos2unix
  # choco install -y pyenv-win psutils dust bottom cheat alacritty
  # choco install -y powershell powershell-core nushell windterm.portable wezterm mobaxterm cmder
  # choco install -y starship oh-my-posh

  # install scoop
  # 以管理员身份运行
  # Set-ExecutionPolicy RemoteSigned -scope CurrentUser
  # 以非管理员身份运行
  # iwr -useb https://gitee.com/glsnames/scoop-installer/raw/master/bin/install.ps1 | iex
  # scoop config SCOOP_REPO 'https://gitee.com/glsnames/scoop-installer'
  # scoop update
  # cd ~/scoop/buckets/main/
  # git remote set-url origin https://gitee.com/scoop-bucket/main.git
  # scoop bucket add extras https://gitee.com/scoop-bucket/extras.git
  # scoop bucket add dorado https://gitee.com/scoop-bucket/dorado.git
  # scoop bucket add nerd-fonts https://gitee.com/scoop-bucket/nerd-fonts.git
  # scoop bucket add versions https://gitee.com/scoop-bucket/versions.git
  # scoop bucket add backit https://gitee.com/scoop-bucket/backit.git
  # scoop bucket add scoopet https://github.com/ivaquero/scoopet.git
  # scoop update

  # scoop install sudo neofetch scoop-completion cmder gow
  # scoop install sudo
  # sudo scoop install 7zip git openssh --global
  # scoop install aria2 curl grep sed less touch
  # scoop install python ruby go perl
}

function git_setup() {
  Write-Output "setup git"
}

function install_powerline_fonts() {
  # install powerline fonts
  # SYNOPSIS
  #     Installs the provided fonts.
  # DESCRIPTION
  #     Installs all the provided fonts by default.  The FontName
  #     parameter can be used to pick a subset of fonts to install.
  # EXAMPLE
  #     C:\PS> ./install.ps1
  #     Installs all the fonts located in the Git repository.
  # EXAMPLE
  #     C:\PS> ./install.ps1 furamono-, hack-*
  #     Installs all the FuraMono and Hack fonts.
  # EXAMPLE
  #     C:\PS> ./install.ps1 d* -WhatIf
  #     Shows which fonts would be installed without actually installing the fonts.
  #     Remove the "-WhatIf" to install the fonts.
  Write-Output "install powerline fonts now!!!"
  # git clone https://github.com/powerline/fonts.git --depth=1
  git clone https://gitee.com/lgf1244/fonts.git --depth=1
  # Set-ExecutionPolicy Bypass -Scope Process -Force; ./fonts/install.ps1
  Set-ExecutionPolicy Bypass -Scope Process -Force; ./fonts/install.ps1 furamono-, hack-*
  Remove-Item -LiteralPath "./fonts" -Force -Recurse
}


function dotfiles_setup() {
  if (!(Test-Command git)) {
    Write-Output "install git by chocolatey now!!!"
    choco install -y git
  }
  else {
    if (!(test-path ~/.dotfiles)) {
      Write-Output "clone dotfiles from gitee.com now!!!"
      git clone git@gitee.com:lgf1244/dotfiles.git ~/.dotfiles
    }
    else {
      # $target="D:\dev-env\msys64\home\lgf\.dotfiles"
      # $link=$env:UserProfile + "\.dotfiles"
      # _lns $target $link

      # $target="D:\dev-env\msys64\home\lgf\.ssh"
      # $link=$env:UserProfile + "\.ssh"
      # _lns $target $link

      Write-Output "setup powershell dotfiles"
      $target = $env:UserProfile + "\.dotfiles\powershell\WindowsPowerShell"
      $link = $env:UserProfile + "\Documents\WindowsPowerShell"
      # _lns($target,$link)
      _lns $target $link
      $target = $env:UserProfile + "\.dotfiles\powershell\PowerShell"
      $link = $env:UserProfile + "\Documents\PowerShell"
      _lns $target $link

      Write-Output "setup windows terminal dotfiles"
      # C:\Users\lgf\AppData\Local\Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json
      $target = $env:UserProfile + "\.dotfiles\windows-terminal\settings.json"
      $link = $env:UserProfile + "\AppData\Local\Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json"
      _lns $target $link

      Write-Output "setup vscode dotfiles"
      # C:\Users\lgf\AppData\Roaming\Code\User
      $target = $env:UserProfile + "\.dotfiles\vscode\settings.json"
      $link = $env:UserProfile + "\AppData\Roaming\Code\User\settings.json"
      _lns $target $link
      $target = $env:UserProfile + "\.dotfiles\vscode\keybindings.json"
      $link = $env:UserProfile + "\AppData\Roaming\Code\User\keybindings.json"
      _lns $target $link

      Write-Output "setup starship dotfiles"
      $target = $env:UserProfile + "\.dotfiles\.config\starship.toml"
      $link = $env:UserProfile + "\.config\starship.toml"
      _lns $target $link

      Write-Output "setup gitconfig dotfiles"
      $target = $env:UserProfile + "\.dotfiles\.gitconfig"
      $link = $env:UserProfile + "\.gitconfig"
      _lns $target $link

      Write-Output "setup wezterm dotfiles"
      $target = $env:UserProfile + "\.dotfiles\wezterm"
      $link = $env:UserProfile + "\.config\wezterm"
      _lns $target $link

      Write-Output "setup git dotfiles"

      Write-Output "setup npm dotfiles"

      Write-Output "setup rust dotfiles"

      Write-Output "setup golang dotfiles"

      Write-Output "setup vim dotfiles"
      Invoke-WebRequest -Uri https://gitee.com/mirrorvim/vim-fast/raw/master/vimrc-no-plug -OutFile ~/_vimrc


      Write-Output "setup neovim dotfiles"

      Write-Output "setup emacs dotfiles"

      Write-Output "setup helix dotfiles"

      Write-Output "setup rime dotfiles"

      Write-Output "setup Espanso dotfiles"



    }
  }
}

function environment_setup() {
  # msys2 环境变量设置
  [Environment]::SetEnvironmentVariable("MSYS2_HOME", "D:\dev-env\msys64", "Machine")
  [environment]::SetEnvironmentvariable("PATH", "$([environment]::GetEnvironmentvariable("Path", "Machine"));%MSYS2_HOME%;%MSYS2_HOME%\mingw64\bin;%MSYS2_HOME%\clang64\bin;%MSYS2_HOME%\ucrt64\bin;%MSYS2_HOME%\usr\bin", "Machine")



  # # 使用powershell 进行环境变量设置: https://zhuanlan.zhihu.com/p/424377493
  # # rust 环境变量设置
  # Write-Output "setup rust Environment by powershell"
  # [Environment]::SetEnvironmentVariable("CARGO_HOME", "$home\.cargo", "User")
  # [Environment]::SetEnvironmentVariable("RUSTUP_HOME", "$home\.rustup", "User")
  # [Environment]::SetEnvironmentVariable("RUSTUP_DIST_SERVER", "http://mirrors.ustc.edu.cn/rust-static", "Machine")
  # [Environment]::SetEnvironmentVariable("RUSTUP_UPDATE_ROOT", "http://mirrors.ustc.edu.cn/rust-static/rustup", "Machine")
  # [environment]::SetEnvironmentvariable("PATH", "$([environment]::GetEnvironmentvariable("Path", "User"));%CARGO_HOME%\bin", "User")


  # # golang环境变量设置
  # Write-Output "setup golang Environment by powershell"
  # [Environment]::SetEnvironmentVariable("GO111MODULE", "on", "Machine")
  # [Environment]::SetEnvironmentVariable("GOPROXY", "https://goproxy.cn", "Machine")
  # [Environment]::SetEnvironmentVariable("GOPATH", "D:\dev-env\Go\go", "User")
  # [Environment]::SetEnvironmentVariable("GOROOT", "D:\dev-env\Go", "Machine")
  # [environment]::SetEnvironmentvariable("PATH", "$([environment]::GetEnvironmentvariable("Path", "User"));%GOPATH%\bin", "User")
  # [environment]::SetEnvironmentvariable("PATH", "$([environment]::GetEnvironmentvariable("Path", "Machine"));%GOROOT%\bin", "Machine")

  # # Anaconda环境变量设置
  # Write-Output "setup anaconda Environment by powershell"
  [Environment]::SetEnvironmentVariable("ANACONDA3_HOME", "D:\dev-env\Anaconda3", "Machine")
  [environment]::SetEnvironmentvariable("PATH", "$([environment]::GetEnvironmentvariable("Path", "Machine"));%ANACONDA3_HOME%;%ANACONDA3_HOME%\Scripts;%ANACONDA3_HOME%\Library\bin;%ANACONDA3_HOME%\Library\mingw-w64\bin;%ANACONDA3_HOME%\Library\usr\bin", "Machine")

  # # java环境变量设置
  # Write-Output "setup java Environment by powershell"
  # # 添加java
  [Environment]::SetEnvironmentVariable('JAVA_HOME', 'C:\Program Files\Java\jdk1.8.0_311' , 'Machine')
  # 添加java到path
  $path = [Environment]::GetEnvironmentVariable('Path', 'Machine')
  $newpath = '%JAVA_HOME%' + '\bin;' + $path # 或者：$newpath = $Env:JAVA_HOME + '\bin;' + $path
  [Environment]::SetEnvironmentVariable('Path', $newpath, 'Machine')
  # # 删除java
  # # [Environment]::SetEnvironmentVariable('JAVA_HOME', $null, 'Machine')
}






Write-Output "wellcome to powershell cross-platform"
Write-Output "current powershell version: $($PSVersionTable.PSEdition)-$($PSVersionTable.PSVersion)"

# $PSVersionTable.OS
# linux(ubuntu): Linux 5.4.0-137-generic #154-Ubuntu SMP Thu Jan 5 17:03:22 UTC 2023
# macos: Darwin 17.7.0 Darwin Kernel Version 17.7.0: Thu Jun 21
# windows(win10-22H2): Microsoft Windows 10.0.19045

# $IsLinux IsMacOS IsWindows 这三个变量是powershell-core 6之后的版本添加上去的， 通用性不高
# Linux系统
if ($IsLinux) {
  Write-Output "this is linux system"

}
# macos系统
if ($IsMacOS) {
  Write-Output "this is macos system"
}
# Windows系统
if (($IsWindows) -or ($($PSVersionTable.PSEdition -like "*Desktop*"))) {
  Write-Output "this is windows system"
  $os = (Get-CimInstance -Class Win32_OperatingSystem).Caption
  Write-Output "current OS: $os"
  # DOS批处理不支持将UNC路径作为当前目录怎么办
  reg add "HKEY_CURRENT_USER\Software\Microsoft\Command Processor" /v "DisableUNCCheck" /t "REG_DWORD" /d "1" /f
  # 双系统时间不同步
  reg add HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation /v RealTimeIsUniversal /t REG_DWORD /d 1
  # (Get-CimInstance -Class Win32_OperatingSystem).Caption -like "*7*" # win7
  # (Get-CimInstance -Class Win32_OperatingSystem).Caption -like "*8*" # win7
  # (Get-CimInstance -Class Win32_OperatingSystem).Caption -like "*7*" # win8/win8.1
  # (Get-CimInstance -Class Win32_OperatingSystem).Caption -like "*10*" # win10
  # (Get-CimInstance -Class Win32_OperatingSystem).Caption -like "*11*" # win11
  # (Get-CimInstance -Class Win32_OperatingSystem).Caption -like "*2012 r2*"  # 2012-R2

  # powershell_setup

  # setup_wsl2

  # install_chocolatey

  git_setup

  # BUG: powershell-core 安装字体的时候出错，即已经有的字体会弹出提示覆盖对话框， powershell-5 则没有问题
  # install_powerline_fonts

  dotfiles_setup

  # environment_setup

}







